package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.LocationAdapter;
import com.sx.gongzhong.model.LocationBean;
import com.sx.gongzhong.port.PermissionsResultListener;
import com.sx.gongzhong.utils.AppConstants;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.widget.LoadDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 位置选择
 */
public class LocationActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    public LocationClient mLocationClient = null;
    private List<PoiInfo> locationLists=new ArrayList<>();
    private LocationAdapter locationAdapter;
    private PoiSearch mPoiSearch,mPoiSearch1,mPoiSearch2;
    private MyBDLocationListener mBDLocationListener;
    private String currentCity="德令哈";


    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_location);
        setTitleName("地理位置选择");
        ButterKnife.bind(this);
        setRightImage(R.mipmap.icon_nav_search);
        performRequestPermissions(AppConstants.LOCATION_PERMISSIONS, 100, new PermissionsResultListener() {
            @Override
            public void onPermissionGranted() {
                initViews();
            }
            @Override
            public void onPermissionDenied() {
                ToastUtils.showToast(LocationActivity.this,"请前往设置中，开启定位权限才可使用");
            }
        });
    }
    private void initViews() {
        try {
            LoadDialog.show(LocationActivity.this,"加载中...");
            mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
            // 注册监听
            mBDLocationListener=new MyBDLocationListener();
            mLocationClient.registerLocationListener(new MyBDLocationListener());

            LocationClientOption option = new LocationClientOption();
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
            option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
            option.setScanSpan(1000);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
            option.setOpenGps(true);//可选，默认false,设置是否使用gps
            option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
            option.setIgnoreKillProcess(false);
            //可选，定位SDK内部是一个service，并放到了独立进程。
            //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
            option.SetIgnoreCacheException(false);
            //可选，设置是否收集Crash信息，默认收集，即参数为false
            option.setIgnoreKillProcess(false);
            option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
            option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        }catch (Exception e){
            e.printStackTrace();
            LoadDialog.dismiss(LocationActivity.this);
            ToastUtils.showToast(LocationActivity.this,"获取位置异常 请检查网络");
        }
    }

    @OnClick({R.id.tv_Default,R.id.imv_Right})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_Default:
                setResult(RESULT_OK,new Intent());
                finish();
                break;
            case R.id.imv_Right:
                startActivityForResult(new Intent(this,LocationSelectActivity.class)
                        .putExtra("City",currentCity),101);
                break;
        }
    }

    /**
     * 展示数据
     */
    private void showAdapter() {
        if (locationAdapter==null){
            recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
            locationAdapter=new LocationAdapter(this,R.layout.item_location_list,locationLists);
            locationAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
            recyclerView.setAdapter(locationAdapter);
            locationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    PoiInfo poiInfo=locationLists.get(position);
                    LocationBean bean=new LocationBean(poiInfo.location.latitude,
                            poiInfo.location.longitude,poiInfo.name);
                    Intent intent=new Intent();
                    intent.putExtra("Location",bean);
                    setResult(RESULT_OK,intent);
                    finish();
                }
            });
        }else {
            locationAdapter.notifyDataSetChanged();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 101://位置选择
                    LocationBean info= (LocationBean) data.getSerializableExtra("Location");
                    if (info!=null){
                        Intent intent=new Intent();
                        intent.putExtra("Location",info);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                    break;
            }
        }
    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){
        public void onGetPoiResult(PoiResult poiResult){
            LoadDialog.dismiss(LocationActivity.this);
            //获取POI检索结果
            if (poiResult != null) {
                if (poiResult.getAllPoi()!=null&&poiResult.getAllPoi().size()>0){
//                    locationLists.clear();
                    if (locationLists != null){
                        locationLists.addAll(poiResult.getAllPoi());
                    }
                    showAdapter();
                }else {
//                    ToastUtils.showToast(LocationActivity.this,"没有搜索出附近房屋");
                }
            }else {
                ToastUtils.showToast(LocationActivity.this,"获取位置失败 请检测网络");
            }
        }
        public void onGetPoiDetailResult(PoiDetailResult result){}
        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {}
    };


    /**
     * 百度定位 获取当前经纬度
     */
    private class MyBDLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                // 根据BDLocation 对象获得经纬度以及详细地址信息
                currentCity=location.getCity();
                mPoiSearch = PoiSearch.newInstance();
                mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
                mPoiSearch.searchNearby(new PoiNearbySearchOption()
                        .keyword("房屋")
                        .sortType(PoiSortType.distance_from_near_to_far)
                        .location(new LatLng(location.getLatitude(),location.getLongitude()))
                        .radius(2000)
                        .pageCapacity(20)
                        .pageNum(1));
                mPoiSearch1 = PoiSearch.newInstance();
                mPoiSearch1.setOnGetPoiSearchResultListener(poiListener);
                mPoiSearch1.searchNearby(new PoiNearbySearchOption()
                        .keyword("酒店")
                        .sortType(PoiSortType.distance_from_near_to_far)
                        .location(new LatLng(location.getLatitude(),location.getLongitude()))
                        .radius(2000)
                        .pageCapacity(20)
                        .pageNum(1));
                mPoiSearch2 = PoiSearch.newInstance();
                mPoiSearch2.setOnGetPoiSearchResultListener(poiListener);
                mPoiSearch2.searchNearby(new PoiNearbySearchOption()
                        .keyword("美食")
                        .sortType(PoiSortType.distance_from_near_to_far)
                        .location(new LatLng(location.getLatitude(),location.getLongitude()))
                        .radius(2000)
                        .pageCapacity(20)
                        .pageNum(1));
                if (mLocationClient.isStarted()) {
                    // 获得位置之后停止定位
                    LoadDialog.show(LocationActivity.this,"获取城市");
                    mLocationClient.stop();
                }
            }else {
                LoadDialog.dismiss(LocationActivity.this);
                ToastUtils.showToast(LocationActivity.this,"获取位置失败 请检测网络");
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mPoiSearch!=null){
            mPoiSearch.destroy();
        }
        if (mPoiSearch1!=null){
            mPoiSearch1.destroy();
        }
        if (mPoiSearch2!=null){
            mPoiSearch2.destroy();
        }
        // 取消监听函数
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(mBDLocationListener);
        }
        if (locationLists != null){
            locationLists = null;
        }
        super.onDestroy();
    }
}